//
//  UnFinishedTableView.m
//  1gene
//
//  Created by 1jiyin on 16/3/24.
//  Copyright © 2016年 1jiyin. All rights reserved.
//
#import "UILabel+VerticalAlign.h"
#import "UnFinishedTableView.h"

@interface UnFinishedTableView()

@property(nonatomic,assign)NSInteger deleteIndex;

@property(nonatomic,copy)UIAlertView *alert;

@end


@implementation UnFinishedTableView
-(instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    if (self=[super initWithFrame:frame style:style]) {
        self.delegate=self;
        self.dataSource=self;
        self.showsVerticalScrollIndicator=NO;
        self.tableHeaderView=[UIView new];
        self.tableFooterView=[UIView new];
        //[self initData];
        UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
        // lpgr.minimumPressDuration = 1; //seconds  设置响应时间
        [self addGestureRecognizer:lpgr]; //启用长按事件
    }
    return self;
}
//删除订单
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer  //长按响应函数
{
    CGPoint p = [gestureRecognizer locationInView:self];
    
    
    NSIndexPath *indexPath = [self indexPathForRowAtPoint:p];//获取响应的长按的indexpath
    if (indexPath == nil) {
        return;
    }else{
        NSLog(@"点击了哪一个cell======%ld",indexPath.row);
        _deleteIndex=indexPath.row;
        if (_alert) {
            
        }else{
        _alert=[[UIAlertView alloc]initWithTitle:@"删除订单" message:nil delegate:self cancelButtonTitle:@"删除" otherButtonTitles:@"确定", nil];
            [_alert show];
        }
        
    }
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"======%ld",buttonIndex);
    NSLog(@"index======%ld",_deleteIndex);
    _alert=nil;
    if (buttonIndex==0) {
        
    }else if(buttonIndex==1){
        if (_dataArray.count>_deleteIndex) {
            TradeModel *model=_dataArray[_deleteIndex];
            NSString *tradeId=model.tradeId;
            [_dataArray removeObjectAtIndex:_deleteIndex];
            [self reloadData];
            [self deleteTrade:tradeId];
        }
    }
}



-(void)initData
{
    NSArray *arr=@[@{@"id":@"1001",@"imageUrl":@"myBackground.jpg",@"title":@"心脑血管",@"content":@"天赋基因天赋基因天赋基因天赋基因天赋基因天",@"price":@"1599"},@{@"id":@"1002",@"imageUrl":@"myBackground.jpg",@"title":@"天赋基因",@"content":@"比较郁闷的是，UILabel并不提供设置其垂直对齐方式的选项。所以如果",@"price":@"1000"},@{@"id":@"1003",@"imageUrl":@"myBackground.jpg",@"title":@"心脑血管",@"content":@"2015年卫生组织发现高血压2015年卫生组织发现高血压2015年卫生组织发现高血压",@"price":@"2600"},@{@"id":@"1004",@"imageUrl":@"myBackground.jpg",@"title":@"天赋基因",@"content":@"2015年卫生组织发现高血压",@"price":@"800"}];
    _dataArray=[NSMutableArray arrayWithArray:arr];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    
    TradeModel *model=_dataArray[indexPath.row];
    
    UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 70, 50)];
    //imgView.image=[UIImage imageNamed:_dataArray[indexPath.row][@"imageUrl"]];
    NSString *url=[NSString stringWithFormat:@"%@",model.good[@"image_url"]];
    url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [imgView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"noImage_background"]];
    [cell.contentView addSubview:imgView];
    //标题
    UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imgView.frame)+3, imgView.frame.origin.y, self.frame.size.width-(CGRectGetMaxX(imgView.frame)+3)-80, 50/3.0)];
    title.text=model.good[@"name"];
    title.textColor=[UIColor blackColor];
    title.font=[UIFont systemFontOfSize:15];
    [cell.contentView addSubview:title];
    
    
    //内容
    UILabel *content=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imgView.frame)+3, CGRectGetMaxY(title.frame), self.frame.size.width-(CGRectGetMaxX(imgView.frame)+3)-80, (50/3.0)*2)];
    content.text=model.good[@"short_discription"];
    content.textColor=[UIColor grayColor];
    content.font=[UIFont systemFontOfSize:13.5];
    content.numberOfLines=2;
    [content alignTop];
    [cell.contentView addSubview:content];
    
    //价格
    UILabel *priceLab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(title.frame)+10, title.frame.origin.y, 60, title.frame.size.height)];
    priceLab.text=[NSString stringWithFormat:@"¥%@",model.good[@"promotion_price"]];
    priceLab.font=[UIFont systemFontOfSize:12];
    priceLab.textColor=[UIColor blackColor];
    priceLab.textAlignment=NSTextAlignmentCenter;
    [cell.contentView addSubview:priceLab];
    
    //去结算
    UIButton *payMoneyBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    payMoneyBtn.frame=CGRectMake(priceLab.frame.origin.x, CGRectGetMaxY(priceLab.frame)+(content.frame.size.height-20)/2.0, priceLab.frame.size.width, 20);
    [payMoneyBtn setTitle:@"去结算" forState:UIControlStateNormal];
    [payMoneyBtn setTitleColor:[UIColor colorWithRed:232/255.0 green:151/255.0 blue:0 alpha:1] forState:UIControlStateNormal];
    payMoneyBtn.layer.borderColor=[UIColor colorWithRed:232/255.0 green:151/255.0 blue:0 alpha:1].CGColor;
    payMoneyBtn.layer.borderWidth=1.0;
    payMoneyBtn.layer.cornerRadius=5.0;
    payMoneyBtn.tag=indexPath.row;
    payMoneyBtn.titleLabel.font=[UIFont systemFontOfSize:12];
    [payMoneyBtn addTarget:self action:@selector(payMoney:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:payMoneyBtn];
    
    //分割线
    UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0, 70-1, self.frame.size.width, 1)];
    line.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [cell.contentView addSubview:line];
    
//    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 70)];
//    view.userInteractionEnabled=YES;
//    [cell addSubview:view];
    
//    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
//   // lpgr.minimumPressDuration = 1; //seconds  设置响应时间
//    [cell addGestureRecognizer:lpgr]; //启用长按事件
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TradeModel *model=_dataArray[indexPath.row];
    [self.myDelegate gotoPayMoney:model.tradeId];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    TradeModel *model=_dataArray[indexPath.row];
    [_dataArray removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
    [self deleteTrade:model.tradeId];

}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}



-(void)payMoney:(UIButton *)sender
{
    TradeModel *model=_dataArray[sender.tag];
    [self.myDelegate gotoPayMoney:model.tradeId];
}


//删除订单
-(void)deleteTrade:(NSString *)tradeId
{
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token= [user objectForKey:@"token"];
    
    [manager DELETE:[NSString stringWithFormat:DeleteTrade,token] parameters:@{@"order_id":tradeId} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"删除订单=======%@",dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error%@",error.localizedDescription);
    }];

}






/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
